<template>
	<view class="neirong">
		<view class="touxiang uni-list-cell-navigate uni-navigate-right" @tap="huantouxiang">
			<text>头像</text>
			<image :src="userInfo.userHeadimg" mode=""></image>
		</view>
		<view class="nicheng uni-list-cell-navigate uni-navigate-right">
			<text>昵称</text>
			<input type="text" value="" v-model="userInfo.userNickname" />
		</view>
		<view class="btn"><button type="primary" @tap="save">保存</button></view>
	</view>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
export default {
	computed: mapState(['URL', 'TOKEN']),
	onLoad() {
		uni.getStorage({
			key: 'USER_INFO',
			success: res => {
				this.userInfo = res.data;
			}
		});
		console.log(this.userInfo);
	},
	data() {
		return {
			userInfo: {},
			isImg: false
		};
	},
	methods: {
		...mapMutations(['TO_UPDATE','GET_USER_INFO']),
		huantouxiang() {
			uni.chooseImage({
				count: 1,
				success: res => {
					this.isImg = true;
					this.userInfo.userHeadimg = res.tempFilePaths[0];
				}
			});
		},
		save() {
			let that = this;
			let reqData = {
				userId: this.userInfo.userId,
				userNickname: this.userInfo.userNickname
			};
			console.log(this.userInfo.userHeadimg);
			if (this.isImg) {
				uni.uploadFile({
					url: this.URL + 'user/uploadImg',
					filePath: this.userInfo.userHeadimg,
					name: 'headImg',
					header: {
						token: this.TOKEN
					},
					formData: reqData,
					success: uploadFileRes => {
						let obj = JSON.parse(uploadFileRes.data);
						console.log(obj);
						if (obj.success) {
							this.getUserInfo(this.TOKEN)
							that.TO_UPDATE(true);
						}
					}
				});
			} else {
				uni.request({
					url: this.URL + 'user/editNickname',
					header: {
						token: this.TOKEN
					},
					data:reqData,
					success: (res) => {
						console.log(res);
						if (res.data.success) {
							this.getUserInfo(this.TOKEN)
							that.TO_UPDATE(true);
						}
					}
				});
			}
		},
		getUserInfo(arg) {
			uni.request({
				url: this.URL + 'user/getUserInformation',
				header: {
					token: arg
				},
				success: res => {
					this.saveUserInfo(res.data.data);
				}
			});
		},
		saveUserInfo(arg){
			uni.setStorage({
				key: 'USER_INFO',
				data: arg,
				success: res => {
					this.GET_USER_INFO();
					this.toMain();
				}
			});
		},
		toMain() {
			uni.navigateBack();
		}
	}
};
</script>

<style lang="scss">
.neirong {
	width: 100%;
	.touxiang {
		image {
			width: 100upx;
			height: 100upx;
			border-radius: 50upx;
			margin-right: 200upx;
		}
	}
	.nicheng {
		input {
		}
	}
	.btn {
		button {
			margin-top: 80px;
			width: 300upx;
		}
	}
}
</style>
